package com.codeoss.framework.service.impl;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.codeoss.framework.context.YunContext;
import com.codeoss.framework.data.metadata.Table;
import com.codeoss.framework.data.store.ITableStore;
import com.codeoss.framework.impexp.ImportManager;
import com.codeoss.framework.response.FileImportResponse;
import com.codeoss.framework.service.IFileImportService;
import com.codeoss.framework.util.ValueNamePair;
import com.codeoss.module.ir.model.IrModel;
import com.codeoss.module.ir.service.IIrModelService;

@Service
public class FileImportService implements IFileImportService {
    @Autowired
    private IIrModelService irModelService;
    @Autowired
    private ImportManager importManager;
    @Autowired
    private ITableStore tableStore;
	@Override
	public FileImportResponse init() {
		// TODO Auto-generated method stub
		FileImportResponse fileImportResponse=new FileImportResponse();
		
		List<ValueNamePair> tableList=new ArrayList<ValueNamePair>();
		fileImportResponse.setTableList(tableList);
		List<IrModel> irModelList=irModelService.list();
		for(int i=0;i<irModelList.size();i++) {
			IrModel irModel=irModelList.get(i);
			ValueNamePair pair=new ValueNamePair(irModel.getName()+"("+irModel.getTableName()+")",irModel.getTableName());
			tableList.add(pair);
		}
		return fileImportResponse;
	}
	
	@Override
	@Transactional
	public FileImportResponse upload(String model, InputStream is,String fileName) {
		// TODO Auto-generated method stub
		FileImportResponse fileImportResponse=new FileImportResponse();
		YunContext yunContext=YunContext.getCurrentContext();
		Table table=tableStore.get(model);
		try {
			if(fileName.endsWith(".xlsx")) {
				importManager.importExcel(yunContext, table, is);
			}else if(fileName.endsWith(".prop")) {
				importManager.importProperties(yunContext, table, is);
			}
		}catch(Exception e) {
			throw new RuntimeException(e);
		}
		
		
		return fileImportResponse;
	}

	
}
